<template>
  <div class="outer">
    <el-tree default-expand-all :expand-on-click-node="false" :data="depts" :props="defaultProps">
      <!-- 节点结构 -->
      <!-- v-slot="{ node, data }" 只能作用在template -->
      <template v-slot="{ data }">
        <el-row
          style="width: 100%; height: 40px"
          type="flex"
          justify="space-between"
          align="middle"
        >
          <el-col>{{ data.name }}</el-col>
          <el-col :span="6">
            <span class="tree-manager">{{ data.managerName }}</span>
            <el-dropdown class="dropdown" @command="handleCommand($event, data.id)">
              <span class="el-dropdown-link">
                操作<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                <el-dropdown-item command="del">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </template>
    </el-tree>
    <!-- 弹层组件 -->
    <add-department ref="addDept" :show-dialog.sync="showDialog" :current-node-id="currentNodeId" @updateDepartment="getDepartments" />
  </div>

</template>

<script>
import { delDepartment, getDepartment } from '@/api/department.js'
import { dataConvertion } from '@/utils/index.js'
import AddDepartment from '@/components/AddDepartment.vue'

export default {
  name: 'Department',
  components: {
    AddDepartment
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false,
      currentNodeId: null // 存储当前点击的id
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    // 获取组织架构数据
    async getDepartments() {
      const res = await getDepartment()
      this.depts = dataConvertion(res, 0)
    },
    // 操作下拉菜单
    async handleCommand(command, id) {
      if (command === 'add') {
        this.showDialog = true
        this.currentNodeId = id
      } else if (command === 'edit') {
        this.showDialog = true
        this.currentNodeId = id // 记录当前操作的id
        this.$nextTick(() => {
          // 父组件调用子组件的方法
          this.$refs.addDept.getDepartmentDetail()
        })
      } else {
        await this.$confirm('您确定要删除该组织架构吗')
        await delDepartment(id)
        this.$message.success('删除成功')
        this.getDepartments() // 重新拉取数据
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin-right: 100px;
}
</style>
